import React, { Component } from "react";
import echarts from 'echarts';
// map
import world_json from '../world3.json';
// api
import http from '../../../utils/request';


const line_Path = 'path://M70.4 787.2l416-457.6c12.8-16 38.4-16 51.2 0l416 457.6c6.4 9.6 19.2 12.8 28.8 12.8 35.2 0 51.2-41.6 28.8-67.2l-448-492.8c-28.8-32-76.8-32-102.4 0L12.8 732.8c-22.4 25.6-3.2 67.2 28.8 67.2 12.8 0 22.4-3.2 28.8-12.8z';

class TopologyCharts extends Component {
    constructor(props){
        super(props);
        this.state = {
          node_data: {}
        };
        this.all_obj = {
          // 所有点的一个对应坐标关系--用于线的坐标查询
          p_obj: {},
          // 基站的正常点集合
          cors_pt_arr: [],
          // 基站报警点收集
          cors_alarm_arr: [],
          // 收集线的数据pT
          pt_lines_arr: [],
          // 报警的收集线
          alarm_lines_arr: [],
          // ===================每个图标不一样的时候就要统一收集
          series: [],
        };
        this.conf = {
          // 
          start: [-180, 80],
          w: 360,
          h: 130,
          padding: 5,
          // 列宽
          _lie_w: 0,
        }
    }

    componentDidMount(){
      var me = this;
      me.fetchTopology();
      me.timer = setInterval(() => {
          // ec_obj.clear();
          me.all_obj.cors_pt_arr.length = 0;
          me.all_obj.cors_alarm_arr.length = 0;
          me.all_obj.pt_lines_arr.length = 0;
          me.all_obj.alarm_lines_arr.length = 0;
          me.all_obj.series.length = 0;

          me._fetchTopology();
      }, 10000)
    }

    componentWillUnmount() {
      this.timer && clearInterval(this.timer)
    }

    _fetchTopology = () => {
      http.get('/info/topology')
      .then(response => {
        const data = response.data.data.items;
        console.log(data)
        this.setState(
          { node_data: data },
          () => this._flow()
        )
      })
    }

    // 获取后台接口数据
    fetchTopology = () => {
      http.get('/info/topology')
      .then(response => {
        const data = response.data.data.items;
        console.log(data)
        this.setState({ node_data: data });
        this.getCharts();
      })
    }

    getCharts = () => {
      var me = this;
      me._bind();
      me._init();
    }

    _bind = () => {
      var me = this;
      echarts.registerMap('world', world_json)
      let dom = document.getElementById('ec')
      // dom.style.width=window.innerWidth*0.759+'px' 
      // dom.style.height=window.innerHeight*0.75+'px'
      console.log(window.innerWidth + 'x' + window.innerHeight)
      let ec_obj = echarts.init(dom)
      ec_obj.clear();

      ec_obj.showLoading();

      var fn = {
        _init: function() {
          // 起始点确定
          me._flow_start_p();
          // 确认列宽
          me._flow_lie_w();
          // 
          me._flow();
        },
        // 起始点确定
        _flow_start_p: function() {
          me.conf.start[0] = me.conf.start[0] + me.conf.padding;
          me.conf.start[1] = me.conf.start[1] - me.conf.padding;
          me.conf.w = me.conf.w - me.conf.padding * 2;
          me.conf.h = me.conf.h - me.conf.padding * 2;
        },
        // 宽度确定
        _flow_lie_w: function() {
          let all_data = me.state.node_data
          console.log(all_data)
          // 数据处理
          var index = 0;
          console.log(me.all_obj)
          // eslint-disable-next-line
          for (var lie in all_data) {
              index++;
          }
          // 初始化列宽
          me.conf._lie_w = Math.floor(me.conf.w / index);
        },
        _flow: function() {
          // **************************************获取数据
          let all_data = me.state.node_data
          console.log('_flow===>all_data: ')
          console.log(all_data)
          for (var lie_key in all_data) {
              // eslint-disable-next-line
              all_data[lie_key].forEach(function(ele, index) {
                // console.log(ele)
                ele.id = `${lie_key}_${index+1}`;
                // ele.name = `lie_${lie_key}_${index+1}`;
                // ele.status = (Math.random() > 0.5 ? 0 : 1);
                // 图标
                ele.icon_id = `${ele.device_type}_${ele.status}`;
              });
          }
          // **********************************************

          // 初始化节点
          me._flow_node(all_data);

          // **************************************模拟数据
          // 模拟要去的数据
          // for (var lie_key_2 in all_data) {
          //     all_data[lie_key_2].forEach(function(ele, index) {
          //     // console.log();
          //     ele.to = me._flow_lines_to_test(ele.id);
          //     });
          // }
          // **********************************************

          // 初始化线
          me._flow_lines(all_data);

          // 生成数据
          me._flow_init();

          // 实时刷新数据
          // setTimeout(() => {
          //     // ec_obj.clear();
          //     me.all_obj.cors_pt_arr.length = 0;
          //     me.all_obj.cors_alarm_arr.length = 0;

          //     me.all_obj.pt_lines_arr.length = 0;
          //     me.all_obj.alarm_lines_arr.length = 0;

          //     me.all_obj.series.length = 0;
          //     me._flow();
          // }, 30000)
        },

        // 初始化节点
        _flow_node: function(all_data) {
          for (var lie in all_data) {
              me._flow_node_init(all_data[lie], lie);
          }
        },
        _flow_node_init: function(arr, lie) {
        // console.log(arr, lie);
        var lie_index = null;
        switch (lie) {
            case "1" : {
              lie_index = 1;
              break;
            }
            case "2" : {
              lie_index = 2;
              break;
            }
            case "3" : {
              lie_index = 3;
              break;
            }
            case "4" : {
              lie_index = 4;
              break;
            }
            case "5" : {
              lie_index = 5;
              break;
            }
            default:
              console.log(lie);
        }
        // 每一列的项目高
        var _item_h = Math.floor(me.conf.h / arr.length);

        // 每列起始经度
        var lng = me.conf.start[0] + (lie_index - 0.5) * me.conf._lie_w;
        // 纬度
        var lat = 0;

        // 
        arr.forEach(function(ele, index) {
            lat = me.conf.start[1] - (index + 1 - 0.5) * _item_h;

            // PT
            if (ele.status) {
              // console.log(ele)
              me.all_obj.series.push({
                type: 'scatter',
                coordinateSystem: 'geo',
                // 涟漪效果
                rippleEffect: {
                scale: 3,
                brushType: 'stroke'
                },

                // 文字标识
                label: {
                  normal: {
                      show: true,
                      position: "bottom",
                      formatter: function(params) {
                        return params.data.name;
                      },
                  }
                },

                // 图标
                symbol: `image://http://ops-dev.raycloud.cn/${ele.icon_id}.png`,
                symbolSize: function(val) {
                  return 48;
                },

                // 模块颜色
                itemStyle: {
                  normal: {
                      // 颜色可以区别对待
                      color: '#00FF00'
                  }
                },

                // 数据
                data: [{
                  id: ele.id,
                  name: `${ele.name}_${ele.ip}`,
                  value: [lng, lat]
                }]
            });
            me.all_obj.cors_pt_arr.push({
              id: ele.id,
              name: ele.name,
              value: [lng, lat]
            });
            }
            // 报警点收集
            else {
            me.all_obj.series.push({
                type: 'effectScatter',  // 带有涟漪特效动画的散点（气泡）图
                coordinateSystem: 'geo',
                // zlevel: 2,
                // 涟漪效果
                rippleEffect: {
                  scale: 3,
                  brushType: 'stroke'
                },

                // 文字标识
                label: {
                normal: {
                    show: true,
                    position: "bottom",
                    formatter: function(params) {
                      return params.data.name;
                    },
                }
                },

                // 图标
                symbol: `image://http://ops-dev.raycloud.cn/${ele.icon_id}.png`,
                symbolSize: function(val) {
                  return 48;
                },

                // 模块颜色
                itemStyle: {
                normal: {
                    // 颜色可以区别对待
                    color: function(params) {
                      // console.log(params);
                      return "red";
                    }
                }
                },

                // 数据
                data: [{
                  id: ele.id,
                  name: `${ele.name}_${ele.ip}`,
                  value: [lng, lat]
                }]
            });

            me.all_obj.cors_alarm_arr.push({
              id: ele.id,
              name: ele.name,
              value: [lng, lat]
            });

            }

            // 生成字典
            me.all_obj.p_obj[ele.id] = [lng, lat];
        });
        },

        // 初始化线
        _flow_lines: function(all_data) {
        for (var lie in all_data) {
            all_data[lie].forEach(function(ele, index) {
              if (ele.to) {
                ele.to.split(',').map(to_one => {
                  // PT
                  if (ele.status) {  // status=1 为PT
                    me.all_obj.pt_lines_arr.push({
                        "coords": [
                          me.all_obj.p_obj[ele.id],
                          me.all_obj.p_obj[to_one],
                        ]
                    });
                  }
                  // 报警线
                  else {
                    me.all_obj.alarm_lines_arr.push({
                        "coords": [
                          me.all_obj.p_obj[ele.id],
                          me.all_obj.p_obj[to_one],
                        ]
                    });
                  }
                  return to_one
                })
              }
              else {  // 没有去向的节点
                console.log('not have to!!!')
              }
            }
          );
        }
        },

        // 
        _flow_init: function() {

        me.all_obj.series.push({
            // name: item[0] + ' Top10',
            type: 'lines',
            zlevel: 1,
            // symbol: ['none', 'arrow'],
            symbolSize: 10,

            effect: {
              show: true,
              period: 1.2,
              trailLength: 0.2,
              color: '#00FF00',
              symbol: line_Path,
              symbolSize: 10
            },

            lineStyle: {
              normal: {
                  color: "rgba(255,255,255,0.2)",
                  width: 1,
                  opacity: 0.1,
                  curveness: 0.1
              }
            },

            data: me.all_obj.pt_lines_arr
        });

        me.all_obj.series.push({
            type: 'lines',
            zlevel: 2,
            // symbol: ['none', 'arrow'],
            symbolSize: 10,

            effect: {
              show: true,
              period: 1.2,
              trailLength: 0.2,
              color: 'red',
              symbol: line_Path,
              symbolSize: 10
            },

            lineStyle: {
              normal: {
                color: "rgba(255,255,255,0.2)",
                width: 1,
                opacity: 0.1,
                curveness: 0.1
              }
            },

            data: me.all_obj.alarm_lines_arr
        });

        const option  = {
            geo: {
              map: 'world',
              // 不显示
              show: false,
              // 当前缩放比
              zoom: 1.3,
              roam: true,

              label: {
                  emphasis: {
                  show: false
                  }
              },

              itemStyle: {
                  normal: {
                  areaColor: '#323c48',
                  borderColor: '#404a59'
                  },
                  emphasis: {
                  areaColor: '#2a333d'
                  }
              }
            },
            series: me.all_obj.series
        };
        console.log(option)

        ec_obj.hideLoading();
        ec_obj.setOption(option);

        // 根据浏览器窗口大小调整
        window.onresize = function() {
          ec_obj.resize();
        };

        // 点击事件
        ec_obj.on('click', { geoIndex: 0, name: 'name1' }, function(params) {
            // me._ec_click(params.data.type, params.data.name, params.data);
            console.log(params);
        });
      },
      };

      for (var k in fn) {
          me[k] = fn[k];
      };
    }

    render(){
        return (
          <div className='appNav'>
            <div id='ec' className='mapNav' style={{height: '100%', width: '100%'}}></div>
          </div>
        )
    }
}

export default TopologyCharts;